package com.example.wu;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    private ImageView nextImg;
    private Button btn;
    private Button btn2;
    private int[] dgs={R.drawable.dg1,R.drawable.dg2,R.drawable.dg3,R.drawable.dg4,R.drawable.dg5,R.drawable.dg6,R.drawable.dg7,R.drawable.dg8,R.drawable.dg9};
    private int index=0;
    private Handler handler;
    private final int CHANGE_DG = 1001;

    //开始默认暂停
    private boolean isPause = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //imageView 图片
        nextImg = findViewById(R.id.nextImg);
        //button 按钮
       /* //上一张
        btn2 = findViewById(R.id.btn2);
*/
        //下一张
        btn = findViewById(R.id.btn);


        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                // handler在初始化时就准备好响应ChangeDG消息
                if (msg.what == CHANGE_DG){
                    index = (index+1)%dgs.length;
                    nextImg.setImageResource(dgs[index]);
                }
                return false;
            }
        });
        /*//上一张
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index=(index-1)%dgs.length;
                if (index<0){
                    index = -index+dgs.length-2;
                }
                nextImg.setImageResource(dgs[index]);
            }
        });*/



                //改用线程，自动切换
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true){
                            try {
                                //在此可设置自动切换的速度
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            // 不能在子线程中修改主线程创建的view
                            // ①创建一个消息并且通过handler发送到主线程
                            if (isPause) {
                                Message message = new Message();
                                message.what = CHANGE_DG;
                                handler.sendMessage(message);
                            }
                        }
                    }
                }).start();


                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isPause = !isPause;
                    }
                });
            }

}
